package com.bjpowernode.other.atomic;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 红包
 */
public class Money implements Runnable{

    //红包总额  保证线程安全
    private AtomicReference<BigDecimal> total;

    public Money(BigDecimal total) {
        this.total = new AtomicReference<>(total);
    }

    @Override
    public void run() {
        while (true) {
            //查看红包剩余金额
            BigDecimal now = total.get();

            //判断红包金额是否小于等于0
            if (now.compareTo(BigDecimal.ZERO) <= 0) {
                System.out.println("红包抢完");
                break;
            }

            //模拟抢红包 没人抢2元
            BigDecimal spend = new BigDecimal("2");//

            //计算被抢之后的余额
            BigDecimal after = now.subtract(spend);

            //自旋
            if (total.compareAndSet(now, after)) {
                System.out.println("剩余：" + total.get());
                break;
            }

        }
    }
}
